package com.example.springboot.service.impl;


import com.example.springboot.common.dto.BorrowListDTO;


import com.example.springboot.common.exception.ServiceException;
import com.example.springboot.common.request.BorrowListRequest;

import com.example.springboot.entity.Borrow;

import com.example.springboot.mapper.BookMapper;
import com.example.springboot.mapper.BorrowMapper;

import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.BorrowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.springboot.common.exception.ExceptionConstant.*;


@Slf4j
@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private UserMapper userMapper;


    /**
     * 根据书名模糊查询
     * @param borrowListRequest
     * @return
     */
    public PageInfo<BorrowListDTO> page(BorrowListRequest borrowListRequest) {
        PageHelper.startPage(borrowListRequest.getPageNum(), borrowListRequest.getPageSize());



        List<BorrowListDTO> borrows = borrowMapper.listByCondition(borrowListRequest);
        return new PageInfo<>(borrows);
    }

    /**
     * 添加图书
     * @param borrow
     * @throws Exception
     */
    public void save(Borrow borrow) throws Exception {
        // 判断该书是否还有剩余
        Integer remainingQuantity = bookMapper.findRemainingQuantityByBookName(borrow.getBookName());
        if(remainingQuantity < 1) {
            throw new ServiceException(Exists_Insufficient_book_stock);
        }

        // 判断用户的积分余额是否大于等于借阅积分
        Integer balance = userMapper.findBalanceByUsername(borrow.getUserName());
        if(balance < borrow.getIntegral()) {
            throw new ServiceException(Exists_Insufficient_user_credit);
        }

        borrow.setUpdateTime(new Date());
        borrowMapper.save(borrow);
    }

    /**
     * 更新图书信息
     * @param borrow
     * @throws Exception
     */
    public void update(Borrow borrow) throws Exception {

        borrow.setUpdateTime(new Date());
        
        borrowMapper.update(borrow);
    }

    /**
     * 根据id获取需要修改的图书信息
     * @param id
     * @return
     */
    public Borrow getById(Integer id) {
        Borrow borrow = borrowMapper.getById(id);
        return borrow;
    }


    /**
     * 根据id删除图书分类
     * @param id
     */
    public void deleteById(Integer id) {

        borrowMapper.deleteById(id);
    }

    

}
